package com.example.project.controller.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Base64;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.project.config.ProjectConfig;
import com.example.project.config.ServerConfig;
import com.example.project.core.domain.AjaxResult;
import com.example.project.utils.StringUtils;
import com.example.project.utils.file.FileUploadUtils;
import com.example.project.utils.file.FileUtils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/common")
public class CommonController {

	private static final Logger log = LoggerFactory.getLogger(CommonController.class);

	@Autowired
	private ServerConfig serverConfig;

	private static final String FILE_DELIMETER = ",";

	/**
	 * 通用下载请求
	 * 
	 * @param fileName 文件名称
	 * @param delete   是否删除
	 */
	@GetMapping("/download")
	public void fileDownload(String fileName, Boolean delete, HttpServletResponse response,
			HttpServletRequest request) {
		try {
			if (!FileUtils.checkAllowDownload(fileName)) {
				throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
			}

			String realFileName = FileUtils.getName(fileName);
			String filePath = ProjectConfig.getProfile() + fileName;// ProjectConfig.getDownloadPath() +

			response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
			FileUtils.setAttachmentResponseHeader(response, realFileName);
			FileUtils.writeBytes(filePath, response.getOutputStream());
			if (delete != null && delete) {
				FileUtils.deleteFile(filePath);
			}
		} catch (Exception e) {
			log.error("下载文件失败", e);
		}
	}

	/**
	 * 通用上传请求（单个）
	 */
	@PostMapping("/upload")
	@ResponseBody
	public AjaxResult uploadFile(MultipartFile file) throws Exception {
		try {
			// 上传文件路径
			String filePath = ProjectConfig.getUploadPath();
			// 上传并返回新文件名称
			String fileName = FileUploadUtils.upload(filePath, file);
			String url = serverConfig.getUrl() + fileName;
			AjaxResult ajax = AjaxResult.success();
			ajax.put("url", url);
			ajax.put("fileName", fileName);
			ajax.put("newFileName", FileUtils.getName(fileName));
			ajax.put("originalFilename", file.getOriginalFilename());
			ajax.put("fileSize", file.getSize());
			return ajax;
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 * 通用上传请求（多个）
	 */
	@PostMapping("/uploads")
	@ResponseBody
	public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
		try {
			// 上传文件路径
			String filePath = ProjectConfig.getUploadPath();
			List<String> urls = new ArrayList<String>();
			List<String> fileNames = new ArrayList<String>();
			List<String> newFileNames = new ArrayList<String>();
			List<String> originalFilenames = new ArrayList<String>();
			List<Long> fileSizes = new ArrayList<Long>();
			for (MultipartFile file : files) {
				// 上传并返回新文件名称
				String fileName = FileUploadUtils.upload(filePath, file);
				String url = serverConfig.getUrl() + fileName;
				urls.add(url);
				fileNames.add(fileName);
				newFileNames.add(FileUtils.getName(fileName));
				originalFilenames.add(file.getOriginalFilename());
				fileSizes.add(file.getSize());
			}
			AjaxResult ajax = AjaxResult.success();
			ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
			ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
			ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
			ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
			ajax.put("fileSize", StringUtils.join(fileSizes, FILE_DELIMETER));
			return ajax;
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 * Base64图片上传
	 */
	@PostMapping("/uploadBase64")
	@ResponseBody
	public AjaxResult uploadBase64Image(@RequestBody String base64Data) throws Exception {
		try {
			// 解析base64数据
			if (base64Data == null || base64Data.trim().isEmpty()) {
				return AjaxResult.error("base64数据不能为空");
			}

			// 提取base64数据部分
			String base64Content;
			if (base64Data.startsWith("data:image/")) {
				// 处理完整的数据URI格式
				int commaIndex = base64Data.indexOf(",");
				if (commaIndex == -1) {
					return AjaxResult.error("base64数据格式不正确");
				}
				base64Content = base64Data.substring(commaIndex + 1);
			} else {
				// 直接是base64内容
				base64Content = base64Data;
			}

			// 解码base64数据
			byte[] imageBytes;
			try {
				imageBytes = Base64.getDecoder().decode(base64Content);
			} catch (IllegalArgumentException e) {
				return AjaxResult.error("base64数据格式错误");
			}

			// 生成文件名
			String fileName = "base64_image_" + System.currentTimeMillis() + ".png";
			// 上传文件路径
			String filePath = ProjectConfig.getUploadPath();

			// 保存文件
			String writeFileName = FileUtils.writeBytes(imageBytes, filePath);

			// 构建返回URL
			String url = serverConfig.getUrl() + writeFileName;

			AjaxResult ajax = AjaxResult.success();
			ajax.put("url", url);
			ajax.put("fileName", writeFileName);
			ajax.put("newFileName", FileUtils.getName(writeFileName));
			ajax.put("originalFilename", fileName);
			return ajax;

		} catch (Exception e) {
			log.error("base64图片上传失败", e);
			return AjaxResult.error("上传失败：" + e.getMessage());
		}
	}

	/**
	 * 本地资源通用下载
	 */
	@GetMapping("/download/resource")
	public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			if (!FileUtils.checkAllowDownload(resource)) {
				throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
			}
			// 本地资源路径
			String localPath = ProjectConfig.getProfile();
			// 数据库资源地址
			String downloadPath = localPath + FileUtils.stripPrefix(resource);
			// 下载名称
			String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
			response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
			FileUtils.setAttachmentResponseHeader(response, downloadName);
			FileUtils.writeBytes(downloadPath, response.getOutputStream());
		} catch (Exception e) {
			log.error("下载文件失败", e);
		}
	}
}
